package com.aote.gradleproject.scheduler;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.boot.task.TaskSchedulerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 张琪
 * @date 2021/7/23 11:17
 */
@Slf4j
@Component
public class QuartzScheduler {
    private static final String JOB_NAME = "inspect_report";
    private static final String JOB_GROUP = "inspect_report_group";
    private static final String TRIGGER_NAME = "inspect_report";
    private static final String TRIGGER_GROUP = "inspect_report_group";
    private static final String JOB_TASK_ID = "job_task_id";

    /**
     * 任务调度器
     */
    @Resource
    private Scheduler scheduler;


    /**
     * 开启任务
     * @throws SchedulerException 定时器执行异常
     */
    public void startJob() throws SchedulerException {
        scheduler.start();
    }

    /**
     * 添加调度任务
     * @param id    调度任务id
     * @param cron  cron时间格式
     * @throws SchedulerException   调度器
     */
    public void add(int id, String cron) throws SchedulerException {
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(JOB_TASK_ID, id);
        jobDataMap.put("userid", id);
        JobDetail jobDetail = JobBuilder.newJob(SchedulerJob.class).usingJobData(jobDataMap)
                .withIdentity(JOB_NAME + id, JOB_GROUP).build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(TRIGGER_NAME + id, TRIGGER_GROUP)
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 删除调度任务
     * @param i 调度id
     * @throws SchedulerException 调度器异常
     */
    public void remove(int i) throws SchedulerException {
        boolean deleteJob = scheduler.deleteJob(new JobKey(JOB_NAME + i, JOB_GROUP));
        log.info(deleteJob ? "任务移除成功" : "任务移除失败");
    }

    /**
     * 初始化注入scheduler
     * @return scheduler 调度器
     * @throws SchedulerException 调度器异常
     */
    @Bean
    public Scheduler scheduler() throws SchedulerException {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        return schedulerFactory.getScheduler();
    }
}
